<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row>
                <!-- 行 -->
                <el-col>
                    <!-- 列 -->
                    <el-button type='primary' @click='addDialogVisible=true'>添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data='roleList' border stripe>
                <!-- 展开列 -->
                <el-table-column type='expand'>
                    <template scope='scope'>
                        <el-row :class='["bnbottom",index==0?"bnhead":"","vcenter"]'
                            v-for='(item,index) in scope.row.children' :key='item.id'>
                            <!-- 渲染一级权限 -->
                            <el-col :span='5'>
                                <el-tag @close='removeRightById(scope.row,item.id)' closable>{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二三级权限 -->
                            <el-col :span='19'>
                                <!-- 通过for循环 嵌套渲染二级权限 -->
                                <el-row :class='[index1==0?"":"bnhead","vcenter"]'
                                    v-for='(item1,index1) in item.children' :key='item1.id'>
                                    <el-col :span='6'>
                                        <el-tag @close='removeRightById(scope.row,item1.id)' closable type='success'>{{item1.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span='18'>
                                        <el-row>
                                            <el-col v-for='(item2,index2) in item1.children' :key='item2.id' :span='6'>
                                                <el-tag @close='removeRightById(scope.row,item2.id)' closable
                                                    type='warning'>{{item2.authName}}</el-tag>
                                            </el-col>
                                        </el-row>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>

                    <!-- <template scope='scope'>
                        代码美化
                        <pre>{{scope.row}}</pre>
                    </template> -->
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type='index' label="/"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <!-- <el-table-column  label="描述">
                    <template scope='scope'>
                        {{scope.row}}
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width='300px'>
                    <template scope='scope'>
                        <!-- 修改按钮 -->
                        <el-button size='mini' type="primary" icon="el-icon-edit" @click='showEditDialog(scope.row.id)'>
                            编辑</el-button>
                        <!-- 删除按钮 -->
                        <el-button size='mini' type="danger" icon="el-icon-delete"
                            @click='removeUserById(scope.row.id)'>删除</el-button>
                        <el-button size='mini' type="warning" icon="el-icon-setting" @click='showSetRightDialog(scope.row)'>分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加用户的对话框 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
            <!-- 内容主体区域 -->
            <el-form :model="addform" :rules="addformrules" ref="addformref">
                <el-row :gutter="20">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-col :span="20">
                            <el-input v-model="addform.roleName"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
                <el-row :gutter="20">
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-col :span="20">
                            <el-input v-model="addform.roleDesc"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="adduser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 展示/编辑 用户对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close='editDialogClose'>
            <!-- 填写的表单 -->
            <!-- 内容主体区域 -->
            <el-form :model="editForm" :rules="editFormRule" ref="editformRef">
                <el-row :gutter="20">
                    <el-form-item label=" 角 色 的 ID ">
                        <el-col :span="20">
                            <el-input v-model="editForm.roleId" disabled></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
                <el-row :gutter="20">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-col :span="20">
                            <el-input v-model="editForm.roleName"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
                <el-row :gutter="20">
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-col :span="20">
                            <el-input v-model="editForm.roleDesc"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 展示分配权限的对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close='setRightDialogClose'>
            <!-- 内容主体区域 树形控件 -->
            <el-tree ref="treeRef" :default-checked-keys='defKeys' default-expand-all node-key='id' show-checkbox :data="rightList" :props="treeProps" ></el-tree>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: 'Roles',
        created() {
            this.getRoleList()
        },
        data() {
            return {
                // 角色列表数据
                roleList: [],

                // 对话框的显示和隐藏
                addDialogVisible: false,
                // 添加的一个角色的表单数据
                addform: {
                    roleName: '',
                    roleDesc: '',
                },
                // 添加表单验证规则对象  
                addformrules: {
                    roleName: [
                        { required: true, message: '请输入角色的名称', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    ],
                    roleDesc: [
                        { required: true, message: '请输入角色的描述', trigger: 'blur' },
                        { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                    ],
                },

                // 修改用户框的显示/隐藏
                editDialogVisible: false,
                // 查询到的角色信息对象
                editForm: {},
                // 修改用户的校验规则
                editFormRule: {
                    roleName: [
                        { required: true, message: '请输入角色的名称', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    ],
                    roleDesc: [
                        { required: true, message: '请输入角色的描述', trigger: 'blur' },
                        { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                    ],
                },

                // 控制分配权限的对话框de显示与隐藏
                setRightDialogVisible:false,
                // 所有权限的数据
                rightList:[],
                // 树形控件的属性绑定对象
                treeProps:{
                    children: 'children',
                    label: 'authName'
                },
                // 默认选中的节点id值 数组
                defKeys:[],
                // 当前即将分配权限的角色id
                roleId:''
            }
        },
        methods: {
            // 获取  角色列表
            async getRoleList() {
                const { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表数据失败！')
                }
                this.roleList = res.data
                // console.log(this.roleList);
            },

            // 监听添加角色对话框的关闭事件-表单的重置
            addDialogClose() {
                this.$refs.addformref.resetFields()
            },
            // 点击按钮 添加新角色-对整个表单进行预验证
            adduser() {
                //接收校验的结果 valid
                this.$refs.addformref.validate(async valid => {
                    // console.log(valid);
                    if (!valid) {// 校验不通过
                        // console.log(!valid,11);
                        return
                    }
                    // 可以发起添加用户的网络请求
                    const { data: res } = await this.$http.post('roles', this.addform)
                    // console.log(res);
                    if (res.meta.status !== 201) {
                        this.$message.error('添加用户失败了！')
                    } else {
                        this.$message.success('添加用户成功！')
                        // 隐藏添加用户的对话框
                        this.addDialogVisible = false
                        // 重新获取用户列表数据
                        this.getRoleList()
                    }
                })
            },

            // 展示/编辑 用户对话框--根据点击事件先把角色查出来，对显示的角色进行修改
            async showEditDialog(id) {
                const { data: res } = await this.$http.get(`roles/${id}`) // `users/${id}` = 'users/' +id
                // console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('查询用户失败！')
                }
                // 赋值
                this.editDialogVisible = true
                this.editForm = res.data
            },
            // 监听修改角色对话框的关闭事件-表单的重置
            editDialogClose() {
                this.$refs.editformRef.resetFields()
            },
            // 点击按钮 修改角色-对整个表单进行预验证
            editUserInfo() {
                //接收校验的结果 valid
                this.$refs.editformRef.validate(async valid => {
                    // console.log(valid);
                    if (!valid) { // 校验不通过
                        // console.log(!valid);
                        return
                    }
                    // 可以发起修改用户的数据请求                                用户id         提交一个用户信息，
                    const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
                    // console.log(res);
                    if (res.meta.status !== 200) {
                        this.$message.error('修改用户失败了！')
                    } else {
                        // 关闭修改的用户的对话框
                        this.editDialogVisible = false
                        // 重新获取用户列表数据--刷新数据
                        this.getRoleList()
                        // 提示修改成功
                        this.$message.success('修改用户成功！')
                    }
                })
            },

            // 根据id删除对应的角色
            removeUserById(id) {
                this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async (suc) => {
                    const { data: res } = await this.$http.delete(`roles/${id}`)
                    console.log(res);
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除用户数据失败！')
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    // console.log(suc,12);
                    this.getRoleList()
                }).catch((err) => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                    // console.log(err);
                });
                // .catch(err => err);
                // 如果用户确认删除，则返回为字符串 confirm
                // 如果用户取消删除，则返回为字符串 cancel
                // console.log(res);
                // if (res !== 'confirm') {
                //     return this.$message.info('已经取消了删除！')
                // }
                // console.log('确认删除！');
            },

            // 根据id删除对应的权限
            async removeRightById(role, rightId) {
                // 弹窗提示用户是否要删除
                const res = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async (suc) => {
                    const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                    // console.log(res);
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除用户权限失败！')
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    // console.log(suc,12);
                    // this.getRoleList()
                    role.children = res.data
                }).catch(err => {
                    if (res !== "confirm") {
                        return this.$message.info('取消了删除！')
                    }
                })
            },

            // 展示 分配权限的对话框
            async showSetRightDialog(role){
                this.roleId=role.id
                // 获取所有的权限
                const {data:res} = await this.$http.get('rights/tree')
                if (res.meta.status!==200) {
                    return this.$message.error('获取权限失败！')
                }
                // 获取到的权限数据  赋值
                this.rightList=res.data

                // 递归获取三级节点的id
                this.getLeafKeys(role,this.defKeys)

                // console.log(this.rightList);
                this.setRightDialogVisible=true
            },
            // 通过递归函数的形式 获取角色下所有的三级权限id 并保存到defKeys 数组中
            getLeafKeys(node,arr){
                // 如果当前 node 节点不包含children 属性 则是三级节点
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(item=>{
                    this.getLeafKeys(item,arr)
                    // console.log(item);
                })
            },
            // 监听分配权限对话框的关闭事件
            setRightDialogClose(){
                this.defKeys=[]
            },
            // 点击 为角色分配权限
            async allotRights(){
                const keys=[
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys()
                ]
                // console.log(keys);
                const idStr = keys.join(',')
                const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
                if (res.meta.status!==200) {
                    return this.$message.error('分配权限失败！')
                }
                this.$message.success('分配权限成功！')
                this.getRoleList()
                this.setRightDialogVisible=false
            }
        },
    }
</script>

<style scoped>
    .el-row {
        margin-bottom: 15px;
    }

    .el-tag {
        margin: 10px;
    }

    .bnhead {
        border-top: 1px solid #eee;
    }

    .bnbottom {
        border-bottom: 1px solid #eee;
    }

    /* 纵向对齐 */
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>